package src;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.sql.*;

public class CustomerInfoPanel extends JDialog {
    private Connection connection;
    private JTable customerTable;
    private JTextField idField, nameField, addressField, phoneField;
    private JButton addButton, updateButton, deleteButton, refreshButton;
    private JPanel inputPanel;
    private JComboBox<String> salesmanCombo;
    private JComboBox<String> waterTypeCombo;

    public CustomerInfoPanel(Connection connection) {
        super((JFrame) null, "客户信息管理", true);
        this.connection = connection;
        setSize(1000, 700);
        setLocationRelativeTo(null);
        getContentPane().setBackground(StyleConstants.BACKGROUND_COLOR);

        // 创建主面板
        JPanel mainPanel = new JPanel(new BorderLayout(10, 10));
        mainPanel.setBackground(StyleConstants.BACKGROUND_COLOR);
        mainPanel.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));

        // 创建标题面板
        JPanel titlePanel = new JPanel();
        titlePanel.setBackground(StyleConstants.THEME_COLOR);
        JLabel titleLabel = new JLabel("客户信息管理", JLabel.CENTER);
        titleLabel.setFont(StyleConstants.TITLE_FONT);
        titleLabel.setForeground(Color.WHITE);
        titlePanel.add(titleLabel);
        mainPanel.add(titlePanel, BorderLayout.NORTH);

        // 创建表格
        String[] columnNames = {"ID", "姓名", "地址", "电话", "业务员", "用水类型"};
        DefaultTableModel model = new DefaultTableModel(columnNames, 0) {
            @Override
            public boolean isCellEditable(int row, int column) {
                return false;
            }
        };
        customerTable = new JTable(model);
        customerTable.setFont(StyleConstants.TABLE_FONT);
        customerTable.getTableHeader().setFont(StyleConstants.TABLE_FONT);
        customerTable.setRowHeight(25);
        customerTable.setGridColor(StyleConstants.THEME_COLOR);
        JScrollPane scrollPane = new JScrollPane(customerTable);
        scrollPane.setBorder(BorderFactory.createEmptyBorder(10, 0, 10, 0));
        mainPanel.add(scrollPane, BorderLayout.CENTER);

        // 创建输入面板
        inputPanel = new JPanel(new GridLayout(7, 2, 10, 10));
        inputPanel.setBackground(StyleConstants.BACKGROUND_COLOR);
        inputPanel.setBorder(BorderFactory.createEmptyBorder(10, 20, 10, 20));

        addInputField(inputPanel, "ID:", idField = new JTextField());
        addInputField(inputPanel, "姓名:", nameField = new JTextField());
        addInputField(inputPanel, "地址:", addressField = new JTextField());
        addInputField(inputPanel, "电话:", phoneField = new JTextField());
        
        // 添加业务员下拉框
        salesmanCombo = new JComboBox<>();
        salesmanCombo.addItem(null);  // 添加一个空选项
        try {
            Statement stmt = connection.createStatement();
            ResultSet rs = stmt.executeQuery("SELECT salesman_id, name FROM salesman");
            while (rs.next()) {
                String salesmanId = rs.getString("salesman_id");
                String salesmanName = rs.getString("name");
                salesmanCombo.addItem(salesmanName + " (" + salesmanId + ")");
            }
        } catch (SQLException e) {
            JOptionPane.showMessageDialog(this, "加载业务员信息失败: " + e.getMessage());
        }
        addComboBox("业务员:", salesmanCombo);
        
        // 添加用水类型下拉框
        waterTypeCombo = new JComboBox<>();
        waterTypeCombo.addItem(null);  // 添加一个空选项
        try {
            Statement stmt = connection.createStatement();
            ResultSet rs = stmt.executeQuery("SELECT type_name FROM water_type");
            while (rs.next()) {
                waterTypeCombo.addItem(rs.getString("type_name"));
            }
        } catch (SQLException e) {
            JOptionPane.showMessageDialog(this, "加载用水类型失败: " + e.getMessage());
        }
        addComboBox("用水类型:", waterTypeCombo);

        // 创建按钮面板
        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 20, 10));
        buttonPanel.setBackground(StyleConstants.BACKGROUND_COLOR);

        addButton = createStyledButton("添加");
        updateButton = createStyledButton("更新");
        deleteButton = createStyledButton("删除");
        refreshButton = createStyledButton("查找");

        buttonPanel.add(addButton);
        buttonPanel.add(updateButton);
        buttonPanel.add(deleteButton);
        buttonPanel.add(refreshButton);

        // 将输入面板和按钮面板添加到主面板
        JPanel bottomPanel = new JPanel(new BorderLayout(10, 10));
        bottomPanel.setBackground(StyleConstants.BACKGROUND_COLOR);
        bottomPanel.add(inputPanel, BorderLayout.CENTER);
        bottomPanel.add(buttonPanel, BorderLayout.SOUTH);
        mainPanel.add(bottomPanel, BorderLayout.SOUTH);

        add(mainPanel);
        refreshTable();

        // 添加表格选择监听器
        customerTable.getSelectionModel().addListSelectionListener(e -> {
            if (!e.getValueIsAdjusting()) {
                int selectedRow = customerTable.getSelectedRow();
                if (selectedRow != -1) {
                    idField.setText(customerTable.getValueAt(selectedRow, 0).toString());
                    nameField.setText(customerTable.getValueAt(selectedRow, 1).toString());
                    addressField.setText(customerTable.getValueAt(selectedRow, 2).toString());
                    phoneField.setText(customerTable.getValueAt(selectedRow, 3).toString());
                    
                    // 设置业务员下拉框选中项
                    String selectedSalesman = customerTable.getValueAt(selectedRow, 4).toString();
                    for (int i = 0; i < salesmanCombo.getItemCount(); i++) {
                        String item = salesmanCombo.getItemAt(i);
                        if (item != null && item.equals(selectedSalesman)) {
                            salesmanCombo.setSelectedIndex(i);
                            break;
                        }
                    }
                    
                    // 设置用水类型下拉框选中项
                    String selectedWaterType = customerTable.getValueAt(selectedRow, 5).toString();
                    for (int i = 0; i < waterTypeCombo.getItemCount(); i++) {
                        String item = waterTypeCombo.getItemAt(i);
                        if (item != null && item.equals(selectedWaterType)) {
                            waterTypeCombo.setSelectedIndex(i);
                            break;
                        }
                    }
                }
            }
        });

        // 添加按钮事件监听器
        addButton.addActionListener(e -> {
            CustomerAddDialog dialog = new CustomerAddDialog(this, connection);
            dialog.setVisible(true);
            refreshTable();
        });
        updateButton.addActionListener(e -> updateCustomer());
        deleteButton.addActionListener(e -> deleteCustomer());
        refreshButton.addActionListener(e -> searchCustomers());

        // 添加输入框回车事件监听器
        idField.addActionListener(e -> searchCustomers());
        nameField.addActionListener(e -> searchCustomers());
        addressField.addActionListener(e -> searchCustomers());
        phoneField.addActionListener(e -> searchCustomers());
    }

    private void addInputField(JPanel panel, String labelText, JTextField textField) {
        JLabel label = new JLabel(labelText);
        label.setFont(StyleConstants.LABEL_FONT);
        panel.add(label);
        textField.setFont(StyleConstants.LABEL_FONT);
        panel.add(textField);
    }

    private void addComboBox(String labelText, JComboBox<String> comboBox) {
        JLabel label = new JLabel(labelText);
        label.setFont(StyleConstants.LABEL_FONT);
        inputPanel.add(label);
        comboBox.setFont(StyleConstants.LABEL_FONT);
        inputPanel.add(comboBox);
    }

    private JButton createStyledButton(String text) {
        JButton button = new JButton(text);
        button.setFont(StyleConstants.BUTTON_FONT);
        button.setBackground(StyleConstants.BUTTON_COLOR);
        button.setForeground(Color.WHITE);
        button.setFocusPainted(false);
        button.setBorderPainted(false);
        button.setCursor(new Cursor(Cursor.HAND_CURSOR));

        // 添加鼠标悬停效果
        button.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseEntered(java.awt.event.MouseEvent evt) {
                button.setBackground(StyleConstants.BUTTON_COLOR.darker());
            }

            public void mouseExited(java.awt.event.MouseEvent evt) {
                button.setBackground(StyleConstants.BUTTON_COLOR);
            }
        });

        return button;
    }

    private void refreshTable() {
        DefaultTableModel model = (DefaultTableModel) customerTable.getModel();
        model.setRowCount(0);
        
        try (Statement stmt = connection.createStatement();
             ResultSet rs = stmt.executeQuery(
                 "SELECT c.*, w.type_name, s.name as salesman_name FROM customer c " +
                 "LEFT JOIN water_type w ON c.water_type_id = w.water_type_id " +
                 "LEFT JOIN salesman s ON c.salesman_id = s.salesman_id")) {
            while (rs.next()) {
                String salesmanName = rs.getString("salesman_name");
                String salesmanId = rs.getString("salesman_id");
                String salesmanDisplay = salesmanName != null ? 
                    salesmanName + " (" + salesmanId + ")" : salesmanId;
                
                model.addRow(new Object[]{
                    rs.getString("customer_id"),
                    rs.getString("name"),
                    rs.getString("address"),
                    rs.getString("phone"),
                    salesmanDisplay,
                    rs.getString("type_name")
                });
            }
        } catch (SQLException e) {
            JOptionPane.showMessageDialog(this, "加载客户数据失败: " + e.getMessage());
        }
    }

    private void updateCustomer() {
        try {
            // 从业务员选择框中提取业务员ID
            String selectedSalesman = salesmanCombo.getSelectedItem().toString();
            String salesmanId = selectedSalesman.substring(selectedSalesman.lastIndexOf("(") + 1, selectedSalesman.lastIndexOf(")"));
            
            // 获取用水类型ID
            String waterTypeId = getWaterTypeId(waterTypeCombo.getSelectedItem().toString());
            if (waterTypeId == null) {
                JOptionPane.showMessageDialog(this, "无效的用水类型！");
                return;
            }

            String sql = "UPDATE customer SET name=?, address=?, phone=?, salesman_id=?, water_type_id=? WHERE customer_id=?";
            PreparedStatement pstmt = connection.prepareStatement(sql);
            pstmt.setString(1, nameField.getText());
            pstmt.setString(2, addressField.getText());
            pstmt.setString(3, phoneField.getText());
            pstmt.setString(4, salesmanId);
            pstmt.setString(5, waterTypeId);
            pstmt.setString(6, idField.getText());
            
            pstmt.executeUpdate();
            JOptionPane.showMessageDialog(this, "客户信息更新成功！");
            clearFields();
            refreshTable();
        } catch (SQLException e) {
            JOptionPane.showMessageDialog(this, "更新客户信息失败: " + e.getMessage());
        }
    }

    private String getWaterTypeId(String typeName) throws SQLException {
        String sql = "SELECT water_type_id FROM water_type WHERE type_name = ?";
        PreparedStatement pstmt = connection.prepareStatement(sql);
        pstmt.setString(1, typeName);
        ResultSet rs = pstmt.executeQuery();
        if (rs.next()) {
            return rs.getString("water_type_id");
        }
        return null;
    }

    private void deleteCustomer() {
        try {
            String sql = "DELETE FROM customer WHERE customer_id=?";
            PreparedStatement pstmt = connection.prepareStatement(sql);
            pstmt.setString(1, idField.getText());
            
            pstmt.executeUpdate();
            JOptionPane.showMessageDialog(this, "客户删除成功！");
            clearFields();
            refreshTable();
        } catch (SQLException e) {
            JOptionPane.showMessageDialog(this, "删除客户失败: " + e.getMessage());
        }
    }

    private void clearFields() {
        idField.setText("");
        nameField.setText("");
        addressField.setText("");
        phoneField.setText("");
        salesmanCombo.setSelectedItem(null);
        waterTypeCombo.setSelectedItem(null);
    }

    private void searchCustomers() {
        DefaultTableModel model = (DefaultTableModel) customerTable.getModel();
        model.setRowCount(0);
        
        try {
            StringBuilder sql = new StringBuilder(
                "SELECT c.*, w.type_name, s.name as salesman_name FROM customer c " +
                "LEFT JOIN water_type w ON c.water_type_id = w.water_type_id " +
                "LEFT JOIN salesman s ON c.salesman_id = s.salesman_id " +
                "WHERE 1=1");
            
            // 添加查询条件
            if (!idField.getText().trim().isEmpty()) {
                sql.append(" AND c.customer_id LIKE ?");
            }
            if (!nameField.getText().trim().isEmpty()) {
                sql.append(" AND c.name LIKE ?");
            }
            if (!addressField.getText().trim().isEmpty()) {
                sql.append(" AND c.address LIKE ?");
            }
            if (!phoneField.getText().trim().isEmpty()) {
                sql.append(" AND c.phone LIKE ?");
            }
            if (salesmanCombo.getSelectedItem() != null) {
                sql.append(" AND c.salesman_id = ?");
            }
            if (waterTypeCombo.getSelectedItem() != null) {
                sql.append(" AND w.type_name = ?");
            }
            
            PreparedStatement pstmt = connection.prepareStatement(sql.toString());
            
            int paramIndex = 1;
            if (!idField.getText().trim().isEmpty()) {
                pstmt.setString(paramIndex++, "%" + idField.getText().trim() + "%");
            }
            if (!nameField.getText().trim().isEmpty()) {
                pstmt.setString(paramIndex++, "%" + nameField.getText().trim() + "%");
            }
            if (!addressField.getText().trim().isEmpty()) {
                pstmt.setString(paramIndex++, "%" + addressField.getText().trim() + "%");
            }
            if (!phoneField.getText().trim().isEmpty()) {
                pstmt.setString(paramIndex++, "%" + phoneField.getText().trim() + "%");
            }
            if (salesmanCombo.getSelectedItem() != null) {
                String selectedSalesman = salesmanCombo.getSelectedItem().toString();
                String salesmanId = selectedSalesman.substring(selectedSalesman.lastIndexOf("(") + 1, selectedSalesman.lastIndexOf(")"));
                pstmt.setString(paramIndex++, salesmanId);
            }
            if (waterTypeCombo.getSelectedItem() != null) {
                pstmt.setString(paramIndex++, waterTypeCombo.getSelectedItem().toString());
            }
            
            ResultSet rs = pstmt.executeQuery();
            while (rs.next()) {
                String salesmanName = rs.getString("salesman_name");
                String salesmanId = rs.getString("salesman_id");
                String salesmanDisplay = salesmanName != null ? 
                    salesmanName + " (" + salesmanId + ")" : salesmanId;
                
                model.addRow(new Object[]{
                    rs.getString("customer_id"),
                    rs.getString("name"),
                    rs.getString("address"),
                    rs.getString("phone"),
                    salesmanDisplay,
                    rs.getString("type_name")
                });
            }
        } catch (SQLException e) {
            JOptionPane.showMessageDialog(this, "查询客户数据失败: " + e.getMessage());
        }
    }
} 